<template>
    <div id="oder-list" v-loading='isLoading'  class="app-container calendar-list-container">
        <div class="filter-container">
            <el-form :inline="true" ref="ruleForm">
                <el-form-item>
                    <el-button icon="el-icon-circle-plus-outline" type='button' class='el-button el-button--primary' @click="dialogFormVisible=true">{{$t('manager.Add_Role')}}</el-button>
                    
                </el-form-item>   
            </el-form> 
        </div>
        <!-- 表格 -->
        <el-table
            :data="tableData"
            border
            v-loading='isLoading'
            style="width: 100%">
            <el-table-column prop="sortId" :label="$t('manager.Number')"> </el-table-column>
            <el-table-column prop="id" label="ID"> </el-table-column>
            <el-table-column prop="roleName" :label="$t('manager.Role_Name')"></el-table-column>
            <el-table-column prop="roleNote" :label="$t('manager.Description')"></el-table-column>
            <el-table-column prop="isFlag" :label="$t('manager.Is_Use')">
                <template slot-scope="scope">
                    {{scope.row.isFlag == 1?$t('manager.Yes'):$t('manager.No')}}
                </template>
            </el-table-column>
            <el-table-column prop="ctime" :label="$t('manager.Time')"> 
                <template slot-scope="scope">  
                            {{scope.row.ctime | parseTime}}
                    </template>
            </el-table-column>
            <el-table-column prop="operate" :label="$t('manager.Operating')" width="200"> 
                <template slot-scope="scope">   
                    <div class="fx" style="display: flex;">
                        <el-button @click="showBindDialog(scope.row.id)"  type='button' icon="el-icon-setting" class='el-button el-button--primary'>{{$t('manager.Bind_Permission')}}</el-button> 
                        <el-button  type='button'  class='el-button el-button--danger' icon="el-icon-delete" @click="deleteBtn(scope.row.id)">{{$t('manager.Delete')}}</el-button> 
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页 -->
        <div class="pagination-container">
            <el-pagination
                background
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="pageSizes"
                :page-size="100"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </div>
        <!-- 新增 -->
        <el-dialog :title="$t('manager.Add_permission_group')" :visible.sync="dialogFormVisible">
            <el-form :model="form" :rules="rules" ref="form">
                <el-form-item prop="roleName" :label="$t('manager.Role')" :label-width="formLabelWidth">
                    <el-input v-model="form.roleName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item prop="roleNote" :label="$t('manager.Role_Description')" :label-width="formLabelWidth">
                    <el-input type="textarea" v-model="form.roleNote" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">{{$t('manager.Cancel')}}</el-button>
                <el-button type="primary" @click="submitForm('form')">{{$t('manager.Submit')}}</el-button>
            </div>
        </el-dialog>
        <!-- //新增权限菜单栏 -->
        <el-dialog :title="dialogTitle" :visible.sync="dialogMenu">
            <el-form :model="addMenuRoles" :rules="menuRules" ref="form">
                <el-form-item prop="interfaceName" label="菜单名" :label-width="formLabelWidth">
                    <el-input v-model="addMenuRoles.interfaceName" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item prop="interfaceUrl" label="接口地址" :label-width="formLabelWidth">
                    <el-input type="text" v-model="addMenuRoles.interfaceUrl" auto-complete="off"></el-input>
                </el-form-item>
                
                <el-form-item prop="interfaceType" :label="$t('manager.Type')" :label-width="formLabelWidth">
                    <el-select v-model="addMenuRoles.interfaceType"  style="width:100%" :placeholder="$t('manager.Please_Choose')">
                        <el-option  :value='1' :label="$t('manager.Module')"/>
                        <el-option  :value='2' :label="$t('manager.Menu')"/>
                        <el-option  :value='3' :label="$t('manager.Button')"/>
                    </el-select>
                </el-form-item>
                <el-form-item prop="pageUrl" :label="$t('manager.Page_identifier')" :label-width="formLabelWidth">
                    <el-input v-model="addMenuRoles.pageUrl" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item  v-if="addMenuRoles.interfaceType != 1" :label="$t('manager.Father_Id')" :label-width="formLabelWidth">
                     <el-select v-model="menuId" :placeholder="$t('manager.Please_Choose')" style="width:100%" @change="getchild">
                        <el-option  :value='menu.id' :label='menu.interfaceName' v-for="menu in menuList" :key="menu.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item v-if="addMenuRoles.interfaceType == 3" :label="$t('manager.Father_Id')" :label-width="formLabelWidth">
                     <el-select v-model="buttonId" :placeholder="$t('manager.Please_Choose')" style="width:100%">
                        <el-option  :value='menu.id' :label='menu.interfaceName' v-for="menu in menuList2" :key="menu.id"/>
                    </el-select>
                </el-form-item>
                <el-form-item prop="orderBy" :label="$t('manager.Order')" :label-width="formLabelWidth">
                    <el-input v-model="addMenuRoles.orderBy" type="number" auto-complete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogMenu = false">{{$t('manager.Cancel')}}</el-button>
                <el-button type="primary" v-if="dialogType == 1" @click="submitFormMenu('form')">{{$t('manager.Submit')}}</el-button>
                <el-button type="primary" v-else  @click="updateMenu()">{{$t('manager.Submit')}}</el-button>
            </div>
        </el-dialog>
        <!-- 绑定权限, 权限列表 -->
        <el-dialog :title="$t('manager.Permission_list')" :visible.sync="dialogBind">
            <div style="margin-bottom:20px">
                <el-button icon="el-icon-circle-plus-outline" type='button' class='el-button el-button--primary' @click="aaa">{{$t('manager.Add_permission_menu')}}</el-button>  
            </div>
            <el-tree
              
                :data="menuList"
                show-checkbox
                node-key="id"
                ref="tree"
                highlight-current
                :render-content="renderContent"
                :props="defaultProps">
            </el-tree>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogBind = false">{{$t('manager.Cancel')}}</el-button>
                <el-button type="primary" @click="setAuthorityByRole">{{$t('manager.Submit')}}</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { 
    getRoleList, 
    addRole, 
    delRole, 
    getAuthorityMenuList, 
    setAuthorityByRole,
    addAuthorityMenu,
    delMenuById,
    getMenuInfoById,
    updateMenu,
    getMenuByCondition,
    getAuthorityByRole
} from '@/api/manager'
export default {
    data() {
        return {
            checkedKeys: [],
            isLoading: false,
            currentPage: 1,
            pageSizes: [10, 20, 30 , 40],
            pageSize: 10,
            total:0,
            tableData: [],
            dialogFormVisible: false,
            dialogMenu: false,
            dialogBind: false,
            formLabelWidth: '140px',
            rules: {
                roleName: [{ required: true, message: this.$t('manager.Role_Name'), trigger: 'blur' },],
                roleNote: [{ required: true, message: this.$t('manager.Role_Description'), trigger: 'blur' },],
            },
            menuRules: {
                name: [{ required: true, message: this.$t('manager.Tip_please_input_menu_name'), trigger: 'blur' },],
                // interfaceUrl: [{ required: true, message: '请输入接口地址', trigger: 'blur' },],
                // pageUrl: [{ required: true, message: '请输入页面标识', trigger: 'blur' },],
                type: [{ required: true, message: this.$t('manager.Tip_please_input_menu_type'), trigger: 'change' },],
                // fid: [{ required: true, message: '请输入父id', trigger: 'blur' },],
                orderBy: [{ required: true, message: this.$t('manager.Tip_please_input_order'), trigger: 'blur' },],
            },
            form: {
               roleName: '',
               roleNote: '',
            },
            menuList: [],
            defaultProps: {
                children: 'sysMenuList',
                label: 'interfaceName'
            },
            addRoleQuery: {
                key: '',
                menus: ''
            },
            addMenuRoles: {
                interfaceName: '',
                interfaceUrl: '',
                pageUrl: '',
                interfaceType: 1,
                fid:'',
                orderBy: ''
            },
            dialogType: 1,
            menuList: [],
            menuList2:[],
            menuId:'',
            buttonId:''            
        }
    },
    methods: {
        //点击新增菜单权限
        aaa(){ 
          if(this.dialogType == 2) {
            this.$refs['form'].resetFields()                      
          } 
          this.dialogType = 1
          this.dialogMenu = true 
        },
        // 获取模块或菜单
        async getMenuByCondition (fid = null) {
            const data = await getMenuByCondition({fid})
            if (data.code === 1) {
                this.menuList = data.data
            }
        },
        async getchild(fid){
            const data = await getMenuByCondition({fid})
            if (data.code === 1) {
                this.menuList2 = data.data
            }
        },     
        // 修改权限菜单
        async updateMenu () {
            console.log(this.addMenuRoles);
            this.$refs['form'].validate(async(valid) => {
                if (valid) {
                    const data = await updateMenu(this.addMenuRoles)
                    if (data.code == 1) {
                        this.$message.success(this.$t('manager.Edit_Succ'))
                        this.resetForm()
                        this.getAuthorityMenuList()
                        this.dialogMenu = false
                    }
                }
            })
           // const { data } = await updateMenu(this.addMenuRoles)
        },
        // 获取菜单权限
        async getMenuInfoById (key) {
            const { data } = await getMenuInfoById({key})
            let temp = {}
            for (const key in data) {
                if (data[key]) {
                    temp[key] = data[key]
                }
            }
            this.addMenuRoles = Object.assign({}, this.addMenuRoles, temp)
        },
        changeDialogType (node, {id}) {
            this.dialogType = 2
            this.getMenuInfoById(id)
            this.dialogMenu = true
        },
        // 删除权限菜单
        async delMenuById (node, {id}) {
            const  data  = await delMenuById({ key: id })
            if (data.code == 1) {
                this.$message.success(this.$t('manager.Delete_Succ'))
                this.getAuthorityMenuList()
            }
        },
        handleSizeChange(val) {
            this.pageSize = val;
            this.getRoleLists()
        },
        handleCurrentChange(val) {
            this.currentPage = val
            this.getRoleLists()
        },
        resetForm(form) {
            this.$refs['form'].resetFields();
        },
        //新增
        submitForm(form) {
            this.$refs['form'].validate(async(valid) => {
                if (valid) {
                    const  data  =  await addRole(this.form)
                    if(data.code == 1) {
                        this.$message({
                            type: 'success',
                            message: this.$t('manager.Tip_add_Succ')
                        })
                        this.getRoleLists()
                        this.dialogFormVisible = false
                    }else {
                        this.$message({
                            type: 'error',
                            message: data.msg
                        })
                    }
                }
            })
            event.stopPropagation
        },
        //角色列表
        async getRoleLists() {
            const  data  = await getRoleList(this.filtersCondition)
            if(data.code == 1) {
                this.total = data.data.total;  
                this.tableData = data.data.records.map((item,index) => {
                    return {
                        sortId:index + 1,
                        ...item,
                    }
                })
            }
        },
        //删除
        async deleteBtn(key) {
            this.$confirm(this.$t('manager.Is_Delete1'), this.$t('manager.Tip'), {
                confirmButtonText: this.$t('manager.Submit'),
                cancelButtonText: this.$t('manager.Cancel'),
                type: 'warning'
            }).then(async () => {
                const  data  = await delRole({
                    key
                })
                if(data.code == 1) {
                    this.$message({
                        type: 'success',
                        message: this.$t('manager.Delete_Succ')
                    });
                    this.getRoleLists()
                }else {
                    this.$message({
                        type: 'success',
                        message: data.msg
                    });
                }
            })
            
        },
        // 菜单列表
        async getAuthorityMenuList () {
            const  data  = await getAuthorityMenuList()
            if (data.code === 1) {
                this.menuList = data.data
            }
        },
        // showBindDialog
        async showBindDialog (key = '') {
            this.dialogBind = true
            this.checkedKeys = []
            this.addRoleQuery.key = key
            const  data  = await getAuthorityByRole({ key })
            if (data.code == 1) {
                this._filter(data.data)
               
                this.checkedKeys = [...new Set([...this.checkedKeys])]
                console.log('====================================');
                console.log(this.checkedKeys);
                console.log('====================================');
                this.$refs.tree.setCheckedKeys(this.checkedKeys);
            }
        },
        // 绑定角色权限
        async setAuthorityByRole (roleId) {
            let res = [...this.$refs.tree.getCheckedKeys(), ...this.$refs.tree.getHalfCheckedKeys()]
            this.addRoleQuery.menus = res.join(',')  
          
            const  data  = await setAuthorityByRole(this.addRoleQuery)
            if (data.code === 1) {
                this.$message.success(this.$t('manager.Bind_Succ'))
                this.getAuthorityMenuList()
                this.dialogBind = false
                this.$forceUpdate()
            }
        },
        // 新增菜单栏
        async submitFormMenu (form) {
            this.$refs['form'].validate(async(valid) => {
                if (valid) {
                  if (this.addMenuRoles.interfaceType == 1) {
                  this.addMenuRoles.fid = ''
                  } else if (this.addMenuRoles.interfaceType == 2) {
                  this.addMenuRoles.fid = this.menuId
                  } else {
                  let isHome = this.menuList.filter(item => item.id == this.menuId)[0].interfaceName
                  console.log(isHome);
                  if (isHome != this.$t('manager.Home_page')) {
                  this.addMenuRoles.fid = this.buttonId
                  } else {
                  this.addMenuRoles.fid = this.menuId
                   }
                  }
                    const data = await addAuthorityMenu({...this.addMenuRoles})
                    if (data.code == 1) {
                        this.$message.success(this.$t('manager.Add_Succ'))
                        this.resetForm()
                        this.getAuthorityMenuList()
                        this.dialogMenu = false
                    }
                }
            })
        },
        renderContent (h, { node, data, store }) {
            var _this = this;
            return (
                <span class="custom-tree-node">
                    <span>{node.label}</span>
                    <span>
                    <el-button size="mini" type="primary" style="margin-right:20px" on-click={ e => { e.stopPropagation(); this.changeDialogType(node, data)}}>{_this.$t('manager.Edit')}</el-button>
                    <el-button size="mini" type="danger" on-click={ e => {e.stopPropagation(); this.delMenuById(node, data)} }>{_this.$t('manager.Delete')}</el-button>
                    </span>
                </span>);
        },
        filterRoles (roles, isHalf = false) {
            this.checkedKeys = this.checkedKeys
            .concat(roles.filter(
                item => {
                    if (item.isFlag == 1) {
                        if (item.interfaceType === 1 && !isHalf) {
                            return false
                        } else if (item.interfaceType === 2 && !isHalf) {
                            if (item.sysMenuList.length > 1) {
                                return false
                            } else {
                                return true
                            }
                            
                        } else {
                            return true
                        }
                    } else {
                        return false
                    }
                   
                }
            ).map(item => item.id))
        },
        _filter (roles, isHalf = false) {
            roles.forEach(role => {
                this.filterRoles(roles, isHalf)
                if (role.sysMenuList && role.sysMenuList.length) {
                    this._filter(role.sysMenuList, role.sysMenuList.length > 1)
                }
            })
            
        }
     
    },
    computed : {
        //请求的过滤条件
        filtersCondition(){
            return {
                offset: this.currentPage,
                limit: this.pageSize,
            }
        },
        dialogTitle () {
            return this.dialogType === 1 ? this.$t('manager.Add_permission_menu') : this.$t('manager.Edit_Permission')
        }
    },
    created() {
        this.getRoleLists()
        
        this.getMenuByCondition()
        this.$nextTick(() => {
            this.getAuthorityMenuList()
        })
    }
}
</script>

<style lang="scss" scoped>
/deep/ .el-tree-node,
/deep/ .custom-tree-node {
margin-bottom: 10px;
}
label {
font-weight: 700;
}
/deep/ .custom-tree-node {
display: flex;
flex: 1;
align-items: center;
justify-content: space-between
}
</style>
